package com.base.cn.platform.os.service.user.user;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.user.ProfileType;
import com.base.cn.platform.os.common.utils.web.WebMobileLoginUtil;
import com.base.cn.platform.os.dao.user.user.UserProfileDao;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.CuserProfile;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.op.affiche.tmp.SendMessage;
import com.base.cn.platform.os.service.user.account.CusUserAccountBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author zjh
 * @Description 第三方登录
 * @Date 2018/8/24 10:27
 */
@Service
public class CuserProfileBiz extends BaseBiz<CuserProfile, UserProfileDao> {
    @Autowired
    protected WebMobileLoginUtil webMobileLoginUtil;
    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private SysConfigBiz sysConfigBiz;
    @Autowired
    private CusUserAccountBiz cusUserAccountBiz;
    @Autowired
    private SendMessage sendMessage;

    /**
     * 修改第三方登录记录绑定的用户
     * @param profile 第三方登录记录对象
     * @param newUserId 新的用户ID
     */
    @Transactional
    public void updateCuserProfileBindingUser(CuserProfile profile, BigDecimal newUserId){
        //原有的用户ID
        BigDecimal oldUserId = profile.getUserId();
        profile.setUserId(newUserId);
        this.updateById(profile,null);
        cusUserBiz.deleteWhereSql(" id="+oldUserId+" and `status`=0");
        cusUserAccountBiz.deleteWhereSql(" userId="+oldUserId);
    }

    /**
     * 多条件查询记录对象
     * @param cuserProfile 查询条件对象
     * @return CuserProfile
     */
    public CuserProfile findCuserProfile(CuserProfile cuserProfile){
        return this.findOne(this.getWhereSql(cuserProfile),null);
    }

    /**
     * 保存第三方登录数据记录
     * @param cuserProfile 第三方登录数据对象
     * @return CuserProfile
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public CuserProfile saveUserProfile(CuserProfile cuserProfile,String registerFrom,boolean iosLogin){
        CuserProfile _cuserProfile = this.findOne("value = '"+cuserProfile.getValue()+"' and profileType='"+cuserProfile.getProfileType()+"'",null);
        if(ObjectUtils.isEmpty(_cuserProfile)){
            TreeMap<String,String> configMap = sysConfigBiz.getSysConfigContext(ConfigName.ONOFF);
            String mobileSwitch = configMap.get("mobileSwitch");

            CusUser user = new CusUser();
            user.setAvatar(cuserProfile.getAvatar());
            user.setNickname(cuserProfile.getName());
            user.setRegisterFrom(registerFrom);
            user.setPassword("111111");
            if (mobileSwitch.equals("ON") && !iosLogin) {//需要绑定手机号
                user.setStatus(0);//临时用户，可删除
            } else {//不需要绑定手机号
                user.setStatus(1);//正常用户，不可删除
            }
            cusUserBiz.createUser(user);
            cuserProfile.setUserId(user.getId());
            this.save(cuserProfile);

            if(user.getStatus() != 0){
                //发送消息
                sendMessage.sendMessage(WXTmpEnum.REGISTER,Arrays.asList(user.getId()),null);
            }

            return cuserProfile;
        }
        return _cuserProfile;
    }

    private String getWhereSql(CuserProfile cuserProfile){
        StringBuilder whereSql =new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(cuserProfile)){
            if(DataUtil.idIsNotNull(cuserProfile.getUserId())){
                whereSql.append(" and userId =").append(cuserProfile.getUserId());
            }
            if(StringUtils.isNotEmpty(cuserProfile.getValue())){
                whereSql.append(" and `value`='").append(cuserProfile.getValue()).append("'");
            }
            if(StringUtils.isNotEmpty(cuserProfile.getProfileType())){
                whereSql.append(" and profileType ='").append(cuserProfile.getProfileType()).append("'");
            }
        }
        return whereSql.toString();
    }

    /**
     *获取第三方登录账号数据
     * @param userIds
     * @return
     */
    public Map<String, List<CuserProfile>> findUserProfileMapList(
            @RequestParam("userIds") String userIds) {
        List<CuserProfile> cuserProfiles = this.find("userId in(" + userIds + ")", null, null);
        String[] split = userIds.split(",");
        Map<String,List<CuserProfile>> map = new HashMap<>();
        for(String userId:split){
            ArrayList<CuserProfile> Profile = new ArrayList<>();
            for (CuserProfile cuserProfile:cuserProfiles){
                if(cuserProfile.getUserId().compareTo(new BigDecimal(userId))==0){
                    Profile.add(cuserProfile);
                }
            }
            map.put(userId,Profile);
        }
        return  map;
    }

}
